package com.ruoyi.websocket.service;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.cfuser.api.rescue.RemoteInitiateService;
import com.ruoyi.cfuser.api.rescue.domain.RescueTask;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import org.etsi.uri.x01903.v13.SignaturePolicyIdentifierType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class GrabOrderService {
    @Autowired
    private RedisService redisService;
    @Resource
    private RemoteInitiateService remoteInitiateService;


    public synchronized AjaxResult grabOrder(Map<String,Object> map) {
    //  解析数据
        ObjectMapper objectMapper = new ObjectMapper();
        RescueTask rescueTask = objectMapper.convertValue(map.get("rescueTask"), RescueTask.class);
        String shopId = objectMapper.convertValue(map.get("shopId"), String.class);
    //  删除redis中的该任务信息
        List<String> cacheList = redisService.getCacheList("taskList" + shopId);
        if (cacheList.size() > 0) {
            for (int i = 0; i < cacheList.size(); i++) {
                RescueTask bean = JSONUtil.toBean(cacheList.get(i), RescueTask.class);
                System.out.println("bean:" + bean);
                if (rescueTask.equals(bean)){
                    cacheList.remove(i);
                    break;
                }
            }
            redisService.deleteObject("taskList" + shopId);

            if (cacheList.size() > 0) {
                redisService.setCacheList("taskList" + shopId, cacheList);
            }
        }

        AjaxResult info = remoteInitiateService.getInfo(rescueTask.getId());
        RescueTask dbRescueTask = objectMapper.convertValue(info.get("data"), RescueTask.class);
        if (dbRescueTask.getStatus() == 1) {    // 已有商家接单
            System.out.println("该订单已被其他商家接单！");
            return AjaxResult.warn("该订单已被其他商家接单！");
        } else if (dbRescueTask.getStatus() == 2) {
            System.out.println("该订单已过期！");
            return AjaxResult.error("该订单已过期！");
        }
        //  该商家接单，改变订单状态
        rescueTask.setStatus(1);
        rescueTask.setMid(Long.parseLong(shopId));
        remoteInitiateService.edit(rescueTask);
        System.out.println("商家已接单");
        return AjaxResult.success("接单成功！");
    }
}
